<template>
  <div>
    <el-card>
      <div class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="全部"
              clearable
              style="width: 200px"
            >
              <el-option label="待审核" value="1" />
              <el-option label="审核通过" value="2" />
              <el-option label="内容违规" value="3" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleData"  v-hasPerm="['resource:posting:get']"><i-ep-search />搜索</el-button>
            <el-button @click="resetQuery">
              <i-ep-refresh />
              重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <div>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="deleteClick()"
          v-hasPerm="['resource:posting:del']"
          ><i-ep-delete />删除</el-button
        >
      </div>
    </el-card>

    <el-card>
      <div>
        <el-form>
          <el-form-item>
            <el-table
              :data="dataList"
							:header-cell-style="{'text-align':'center'}"
   					 :cell-style="{'text-align':'center'}"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="40" align="center" />
              <el-table-column
                fixed
                type="index"
                :index="indexMethod"
                label="序号"
                width="70"
              />
              <el-table-column prop="title" label="标题" width="120" />
              <el-table-column prop="type" label="分类" width="120" />

              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <span v-if="scope.row.status === 1"
                    ><el-tag type="info" size="large">待审核</el-tag></span
                  >
                  <span v-else-if="scope.row.status === 2"
                    ><el-tag type="success" size="large">审核通过</el-tag></span
                  >
                  <span v-else-if="scope.row.status === 3"
                    ><el-tag type="danger" size="large">内容违规</el-tag></span
                  >
                </template>
              </el-table-column>

              <el-table-column prop="authorUsername" label="发布人" width="120" />
              <el-table-column label="图片" width="180">
                <template #default="scope">
                  <!-- <img
                    :src="scope.row.coverImage"
                    alt=""
                    style="width: 100%; height: 100px"
                  /> -->
									<el-image
      							style="width: 100%; height: 100px"
     							 :src="scope.row.coverImage"
     							 :zoom-rate="1.2"
      							:max-scale="7"
     							 :min-scale="0.2"
     							 :preview-src-list="[scope.row.coverImage]"
										:preview-teleported="true"
										hide-on-click-modal
   							 />
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="发布时间" width="170" />

              <el-table-column fixed="right" label="操作" width="330">
                <template #default="scope">
                  <!-- <el-button
                    link
                    type="primary"
                    size="small"
                    v-if="scope.row.status === 1"
                    @click="passClick(scope.row.id)"
                  >
                    审核通过
                  </el-button>
                  <el-button
                    link
                    type="primary"
                    size="small"
                    v-if="scope.row.status === 1"
                    @click="notPassClick(scope.row.id)"
                  >
                    内容违规
                  </el-button> -->

                  <el-button type="primary" @click="detailsClick(scope.row.id)"    v-hasPerm="['resource:posting:get']"
                    >详情</el-button
                  >

									<el-button
                    type="info"
                    @click="handleClick(scope.row)"
										v-hasPerm="['resource:posting:update']"
                    >审核</el-button
                  >

                  <el-button type="warning" @click="openDialog(scope.row.id)"    v-hasPerm="['resource:posting:update']"
                    >编辑</el-button
                  >

                  <el-button type="danger" @click="deleteClick(scope.row.id)"    v-hasPerm="['resource:posting:del']"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页搜索 -->
            <div
              style="
                display: flex;
                justify-content: center;
                width: 100%;
                margin-top: 15px;
              "
            >
              <el-pagination
                background
                layout="sizes, prev,slot, next, jumper"
                :page-count="pageTotal"
                :page-sizes="[10, 20, 30, 50]"
                :current-page="activePager"
                @update:current-page="pageChange"
                @update:page-size="sizeChange"
                :default-current-page="1"
                :default-page-size="10"
              >
                <div class="pagination">
                  <span
                    class="pagination__item"
                    :class="{ active: activePager === pager }"
                    v-for="pager in pageArr"
                    :key="pager"
                    @click="pageChange(pager)"
                  >
                    {{ pager }}
                  </span>
                </div>
              </el-pagination>
            </div>
            <!-- 分页搜索 -->
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-dialog v-model="dialog.visible" title="详细信息" width="70%" top="5vh">
      <el-descriptions border class="px-32px" direction="vertical">
        <el-descriptions-item label="用户名">{{
          postingDetailData?.authorUsername
        }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{
          postingDetailData?.author
        }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{
          postingDetailData?.title
        }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{
          postingDetailData?.typeName
        }}</el-descriptions-item>
        <el-descriptions-item label="标签"
          ><el-tag v-for="item in postingDetailData?.tag" :key="item" class="mr-8px">
            {{ item }}
          </el-tag></el-descriptions-item
        >
        <el-descriptions-item label="状态">
          <span v-if="postingDetailData?.status === 1"
            ><el-tag type="info" size="large">待审核</el-tag></span
          >
          <span v-else-if="postingDetailData?.status === 2"
            ><el-tag type="success" size="large">审核通过</el-tag></span
          >
          <span v-else-if="postingDetailData?.status === 3"
            ><el-tag type="danger" size="large">内容违规</el-tag></span
          >
        </el-descriptions-item>
        <el-descriptions-item label="可视范围">
          {{ postingDetailData?.visible }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ postingDetailData?.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ postingDetailData?.publishTime }}
        </el-descriptions-item>
        <el-descriptions-item label="封面"
          ><img
            :src="postingDetailData?.coverImage"
            alt=""
            style="width: 180px; height: 100px"
        /></el-descriptions-item>
        <el-descriptions-item label="描述">{{
          postingDetailData?.describe
        }}</el-descriptions-item>
      </el-descriptions>
      <v-md-preview :text="postingDetailData?.content"></v-md-preview>
    </el-dialog>

    <el-dialog v-model="editDialog.visible" title="文章编辑" top="5vh">
      <el-form
        ref="detailFormRef"
        class="ml-42px"
        :rules="rules"
        :model="formData"
        :label-position="labelPosition as 'left'"
        label-width="100px"
        style="max-width: 460px"
      >
        <el-form-item label="序号">
          <el-input v-model="formData.id" disable />
        </el-form-item>

        <el-form-item label="作者用户">
          <el-input v-model="formData.authorUsername" />
        </el-form-item>

        <el-form-item label="文章标题">
          <el-input v-model="formData.title" />
        </el-form-item>
        <el-form-item label="文章类型描述">
          <el-input v-model="formData.type" />
        </el-form-item>
        <!-- <el-form-item label="文章标签">
          <el-input v-model="formData.tag" />
        </el-form-item> -->
        <el-form-item label="创建时间">
          <el-input v-model="formData.createTime" />
        </el-form-item>
        <el-form-item label="点赞数量">
          <el-input v-model="formData.likeRecord" />
        </el-form-item>
        <el-form-item label="浏览数量">
          <el-input v-model="formData.browseRecord" />
        </el-form-item>
        <el-form-item label="评论数量">
          <el-input v-model="formData.noc" />
        </el-form-item>
        <el-form-item label="文章评分">
          <el-input v-model="formData.score" />
        </el-form-item>

        <el-form-item label="公开可见 ">
          <el-input v-model="formData.visible" />
        </el-form-item>
        <el-form-item label="文章状态">
          <el-input
            v-model="formData.status"
            :value="getStatusText(formData.status)"
            disabled
          >
            <template #append>
              <el-button
                :icon="Edit"
                @click="
                  dialogExamineVisible.visible = true;
                  blogStatus = formData.status;
                "
              />
            </template>
          </el-input>
          <!-- <div v-if="dialogExamineVisible.visible">
            <el-form :model="formData">
              <el-radio-group v-model="blogStatus">
                <el-radio :label="1" disabled>待审核</el-radio>
                <el-radio :label="2">审核通过</el-radio>
                <el-radio :label="3">内容违规</el-radio>
              </el-radio-group>
            </el-form>
            <span class="dialog-footer">
              <el-button @click="dialogExamineVisible.visible = false">取消</el-button>
              <el-button @click="axamineSubmit(blogStatus, formData.id)" type="primary">
                修改
              </el-button>
            </span>
          </div> -->
        </el-form-item>
        <el-form-item label="发布时间">
          <el-input v-model="formData.publishTime" />
        </el-form-item>
        <el-form-item label="类型名称">
          <el-input v-model="formData.typeName" />
        </el-form-item>
        <el-form-item label="文章标识">
          <el-input v-model="formData.identifier" />
        </el-form-item>
        <el-form-item label="文章内容">
          <el-input v-model="formData.content" />
        </el-form-item>

        <el-form-item label="管理员用户名">
          <el-input v-model="formData.managerUsername" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

		 <!-- 审核 -->
		 <el-dialog v-model="dialogExamineVisible.visible" title="审核信息">
      <el-form :model="formData">
        <el-radio-group v-model="formData.status">
          <el-radio :label="2">审核通过</el-radio>
          <el-radio :label="3">内容违规</el-radio>
        </el-radio-group>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogExamineVisible.visible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="axamineSubmit(formData.status, formData.id)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
// import { Edit } from "@element-plus/icons-vue";
import {
  getResource,
  deleteAdmin,
  updatainfo,
  getDetail,
  examinePass,
  examineNotPass,
} from "@/api/blog";
import { Article, getListInfo } from "@/api/blog/type";
import { reactive, ref } from "vue";
import { ElForm, ElMessageBox } from "element-plus";
import {UploadFilled,Promotion,Plus,Edit} from '@element-plus/icons-vue'
import { useRouter } from "vue-router";

let router = useRouter();

defineComponent({
  components: {
		UploadFilled,
		Promotion,
		Plus,
		Edit,
  },
});


const dataList = ref<Article[]>();
const postingDetailData = ref<Article>();
const loading = ref(false);
const dialogTableVisible = ref(false);

const ids = ref([]);

const formLabelWidth = "140px";

const queryParams = reactive<getListInfo>({
  pageNum: 1,
  pageSize: 10,
});

const indexMethod = (index: number) => {
  return index + (activePager.value - 1) * queryParams.pageSize + 1;
};

//总共页数
const pageTotal = ref(0);
//后端传来的页码数组
const pageArr = ref([]);
//当前页码
const activePager = ref(1);

//审核弹框
const dialogExamineVisible = reactive<DialogOption>({
  visible: false,
});

const dialog = reactive<DialogOption>({
  visible: false,
});

//编辑弹框
const editDialog = reactive<DialogOption>({
  visible: false,
});

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

let formData = reactive<Article>({
  id: 0,
  authorUsername: "",
  title: "",
  type: 0,
  tag: [],
  createTime: "",
  likeRecord: 0,
  browseRecord: 0,
  visible: 0,
  status: 0,
  publishTime: "",
  managerUsername: "",
  coverImage: "",
  content: "",
  noc: 0,
  describe: "",
  author: "",
});
const blogStatus = ref<number>(0);

const queryFormRef = ref(ElForm); // 查询表单

const labelPosition = ref("left");

const detailFormRef = ref(ElForm); // 用户表单

const rules = reactive({
  id: [{ required: true, message: "id不能为空", trigger: "blur" }],
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  describe: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  type: [{ required: true, message: "资源的类型不能为空", trigger: "blur" }],
  path: [{ required: true, message: "路径不能为空", trigger: "blur" }],
  visible: [{ required: true, message: "资源的可见性不能为空", trigger: "blur" }],
  resourceName: [{ required: true, message: "资源的名称不能为空", trigger: "blur" }],
});

//详情审核
function axamineSubmit(status: number, id: number) {
  if (status === 2) {
    passClick(id);
  } else if (status === 3) {
    notPassClick(id);
  }
  dialogExamineVisible.visible = false;
}

//判断状态
function getStatusText(status?: number) {
  if (status === 1) {
    return "待审核";
  } else if (status === 2) {
    return "审核成功";
  } else if (status === 3) {
    return "内容违规";
  } else {
    return "";
  }
}


//删除
async function deleteClick(id?: number) {
  const adminIds = [id || ids.value] as number[];
  if (!adminIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  await ElMessageBox.confirm("确认删除文章?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteAdmin(adminIds).then(() => {
      ElMessage.success("删除成功");
			handleData();
    });
  });
}

async function passClick(id: number) {
  let key = id;
  loading.value = true;
  await examinePass(key)
    .then(() => {
      console.log(2222);
      console.log(key);
      formData.status = blogStatus.value;
      ElMessage.success("审核成功");
      closeDialog();
      resetQuery();
    })
    .finally(() => (loading.value = false));
}

async function notPassClick(id: number) {
  let key = id;
  loading.value = true;
  await examineNotPass(key)
    .then(() => {
      console.log(333);
      console.log(key);
      formData.status = blogStatus.value;
      ElMessage.success("审核成功");
      closeDialog();
      resetQuery();
    })
    .finally(() => (loading.value = false));
}

//打开弹窗
// async function openDialog(row: Article) {
//   editDialog.visible = true;
//   editDialog.title = "修改数据";
//   Object.assign(formData, row);
// }

//审核弹框
async function handleClick(row: Article) {
  dialogExamineVisible.visible = true;
  await Object.assign(formData, row);
}

async function openDialog(id: number) {
  router.push({
    path: "/editBlog/" + id,
  });
}

//修改数据提交
async function handleSubmit() {
  await detailFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      updatainfo(formData)
        .then(() => {
          ElMessage.success("修改成功！");
          closeDialog();
          handleData();
        })
        .finally(() => (loading.value = false));
    }
  });
}
/**
 *
 * @param id 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleData();
}

//详情
async function detailsClick(id: number) {
  postingDetailData.value = undefined;
  dialog.visible = true;
  await getDetail(id).then(({ data }) => {
    Object.assign(formData, data.posting);
    postingDetailData.value = data.posting;
  });
}

function closeDialog() {
  dialog.visible = false;
  editDialog.visible = false;
  dialogExamineVisible.visible = false;
  // handleData();
}

//获取数据
async function handleData() {
  loading.value = true;
  await getResource(queryParams)
    .then(({ data }) => {
      pageTotal.value = data.navigatepageNums[data.navigatepageNums.length - 1];
      pageArr.value = data.navigatepageNums;
      dataList.value = data.postings;
      console.log(dataList);
    })
    .catch((error) => {
      console.error("Error:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}

function pageChange(pageNum: number) {
  queryParams.pageNum = pageNum;
  activePager.value = pageNum;
  handleData();
}

function sizeChange(sizeNum: number) {
  queryParams.pageSize = sizeNum;
  handleData();
}

onMounted(() => {
  handleData();
});
</script>

<style scoped>
.pagination {
  display: flex;
  justify-content: center;
}

.pagination__item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  margin: 0 5px;
  cursor: pointer;
  border: 1px solid #ccc;
}

.pagination__item.active {
  color: white;
  background-color: #4593ff;
}
</style>
